package com.example.flowermall.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.flowermall.entity.*;
import com.example.flowermall.mapper.UserMapper;
import com.example.flowermall.mapper.UserRoleMapper;
import com.example.flowermall.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.flowermall.service.InvitationOrderService;
import com.example.flowermall.service.InvitatonService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author xiaoman
 * @since 2023-05-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    UserMapper userMapper;
    @Autowired
    UserRoleMapper userRoleMapper;
    private final InvitatonService invitatonService;
    private final InvitationOrderService invitationOrderService;

    public UserServiceImpl(InvitatonService invitatonService, InvitationOrderService invitationOrderService) {
        this.invitatonService = invitatonService;
        this.invitationOrderService = invitationOrderService;
    }


    @Override
    @Transactional
    public void addUser(User user) {
        userMapper.insert(user);
        //写入用户角色表
        List<Integer> roleIdList = user.getRoleIdList();
        if(roleIdList!=null){
            for(Integer roleId:roleIdList){
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }

    @Override
    public void delete(Integer id) {
        userMapper.deleteById(id);
        LambdaQueryWrapper<UserRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,id);
        userRoleMapper.delete(queryWrapper);
    }

    @Override
    public User getUserById(Integer id) {
        User user = userMapper.selectById(id);
        LambdaQueryWrapper<UserRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,id);
        List<UserRole> userRoleList = userRoleMapper.selectList(queryWrapper);
        //拿出id
        List<Integer> list = userRoleList.stream().map(userRole -> {return userRole.getRoleId();
        }).collect(Collectors.toList());
        user.setRoleIdList(list);
        return user;
    }

    @Override
    @Transactional
    public void updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
        //清除原有角色
        LambdaQueryWrapper<UserRole> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId,user.getId());
        userRoleMapper.delete(queryWrapper);
        //设置新角色
        List<Integer> roleIdList = user.getRoleIdList();
        if(roleIdList!=null){
            for(Integer roleId:roleIdList){
                userRoleMapper.insert(new UserRole(null,user.getId(),roleId));
            }
        }
    }

    @Override
    public List<User> selectUsers(String username) {
        List<User> user = userMapper.selectUsers(username);
        return user;
    }

    @Override
    public Result register(User user) {
        User user1 = userMapper.selectUser(user.getUsername());
        Boolean isInvitation = getIsInvitation(user.getBeInvitedCode());
        if(isInvitation){
            String code = generateRandomString(6);
            user.setInvitationCode(code);
            if(ObjectUtils.isEmpty(user1)){
                userMapper.insert(user);
                return Result.success("注册成功");
            }else {
                return Result.success("用户已存在");
            }
        }
        return Result.error("邀请码不存在");
    }
    /**判断是否存在*/
    private Boolean getIsInvitation(String beInvitedCode) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getInvitationCode,beInvitedCode);
        User user = userMapper.selectOne(queryWrapper);
        if(ObjectUtils.isEmpty(user)){
            return false;
        }
        return true;
    }

    @Override
    public User wxLogin(User user) {
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername,user.getUsername());
        return userMapper.selectOne(queryWrapper);
    }
    @Override
    public User getUser(Integer id){
        LambdaQueryWrapper<User> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getId,id);
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 获取自己邀请自己的人*/
    @Override
    public List<User> getBeCode(String invitationCode) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getBeInvitedCode,invitationCode);
        return userMapper.selectList(queryWrapper);
    }

    /**
     * 获取邀请自己的人*/
    @Override
    public User getInvitationCode(String beInvitedCode) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getInvitationCode,beInvitedCode);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public User getInvitation(Integer userId) {
        User user = getUser(userId);
        User one = this.getInvitationCode(user.getBeInvitedCode());
        if(!ObjectUtils.isEmpty(one)){
            LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(User::getInvitationCode,one.getBeInvitedCode());
            User selectOne = userMapper.selectOne(wrapper);
            one.setUsers(selectOne);
        }
        return one;
    }

    @Override
    public List<Invitaton> getInvitationList(Integer id) {
        return invitatonService.getByUserId(id);
    }

    @Override
    public Boolean payouts(Integer id) {
        InvitationOrder invitationOrder = invitationOrderService.queryById(id);
        if(!ObjectUtils.isEmpty(invitationOrder)){
            invitationOrder.setStatus("1");
            invitationOrderService.update(invitationOrder);
            User user = userMapper.selectById(invitationOrder.getId());
            user.setRebate(0);
            userMapper.updateById(user);
            return invitatonService.deleteByUserId(invitationOrder.getId());
        }

        return false;
    }

    public static String generateRandomString(int length) {
        Random random = new Random();
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++) {  // 生成10个字符，调整此数字控制字符数量
            if (random.nextBoolean()) {
                // 生成英文字符（大写或小写）
                char englishChar = random.nextBoolean() ?
                        (char) ('A' + random.nextInt(26)) :  // 大写字母
                        (char) ('a' + random.nextInt(26));  // 小写字母
                result.append(englishChar);
            } else {
                // 生成数字字符（0-9）
                char digitChar = (char) ('0' + random.nextInt(10));
                result.append(digitChar);
            }
        }
        return result.toString();
    }



}

